import 'dart:convert';
import 'dart:io';
import 'dart:isolate';

import 'package:flutter_test/flutter_test.dart';
import 'package:im_app/im/dao/ImSettingDao.dart';
import 'package:im_app/im/util/DbUtil.dart';
import 'package:isolate_pool_executor/isolate_pool_executor.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

void main() {
  test("db isolate test", () async {
    var database = await getDatabase();

    await database.delete('im_setting');
    List<Map<String, Object?>> result = await database.query('im_setting');
    print("result: ${result.length}");
    closeDatabase(database);

    var pool = IsolatePoolExecutor.newFixedIsolatePool(2);

    var futures = [];
    var size = 3;
    for (var i=0; i<size; i++) {
      var userId = 't00$i';
      TaskFuture<int> idFuture = pool.compute(insetData, DbParam(content: "hello $i", userId: userId));
      futures.add(idFuture);
    }

    for(var future in futures) {
      var id = await future;
      print('result2: $id');
    }

    var database2 = await getDatabase();
    List<Map<String, Object?>> result2 = await database2.query('im_setting');
    closeDatabase(database2);

    print("result: ${result2.length}, ${Isolate.current.hashCode}");

    assert(result2.length == size);
  });
}

Future<Database> getDatabase() async {
  sqfliteFfiInit();
  databaseFactory = databaseFactoryFfi;
  Database database = await DbUtil.connect("imtest.db");
  return database;
}

Future<int> insetData(DbParam dbParam) async {
  var database = await getDatabase();
  print('thread start, ${Isolate.current.hashCode}');
  var settingDao = SettingDao();
  int id = await settingDao.insert(dbParam.userId, dbParam.userId, dbParam.content);
  print('result: ${id}, ${Isolate.current.hashCode}');
  closeDatabase(database);
  return id;
}

closeDatabase(Database database) {
  database.close();
}

class DbParam {
  // Database database;
  String content;
  String userId;

  DbParam({ required this.content, required this.userId });
}